package org.example.authservice.service.impl;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import org.example.authservice.mapper.UserMapper;
import org.example.authservice.pojo.User;
import org.example.authservice.service.MailService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 周昊
 * @since 2024/12/16 11：34
 * @version 1.0
 */
@Service
public class MailServiceImpl implements MailService {


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JavaMailSenderImpl mailSender;
    public final static int SIX = 6;

    /**
     * 发送邮件验证码
     *
     * @param email 邮箱地址
     * @return 成功返回true，失败返回false
     */
    @Override
    public Boolean getMailVc(String email) throws Exception {
        User user = userMapper.selectByMail(email);
        if (user != null) {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            // 生成6位随机验证码（包含数字和字母）
            StringBuilder verificationCode = new StringBuilder();
            String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            Random random = new Random();
            for (int i = 0; i < SIX; i++) {
                int index = random.nextInt(characters.length());
                verificationCode.append(characters.charAt(index));
            }
            String code = verificationCode.toString();
            System.out.println(code);

            // 构建邮件内容
            String content = "您正在进行邮箱找回密码，您的验证码为：" + code + "，请在5分钟内输入。如非本人操作，请忽略本邮件。";

            // 设置邮件主题、收件人、发件人
            helper.setSubject("音驹平台-验证码");
            helper.setTo(email);
            helper.setFrom("3202741397@qq.com");

            // 创建一个Multipart对象，用于组合邮件的多个部分
            MimeMultipart multipart = new MimeMultipart();

            // 创建一个表示邮件正文的MimeBodyPart
            MimeBodyPart bodyPart = new MimeBodyPart();
            // 设置为HTML格式的正文内容，可根据实际需求调整格式
            bodyPart.setContent(content, "text/html;charset=UTF-8");

            // 将正文的MimeBodyPart添加到Multipart中
            multipart.addBodyPart(bodyPart);

            // 将Multipart对象设置为邮件消息的内容
            mimeMessage.setContent(multipart);

            // 将邮箱验证码以邮件地址为key存入redis，设置5分钟过期时间
            redisTemplate.opsForValue().set(email, code, 300, TimeUnit.SECONDS);

            // 发送邮件
            mailSender.send(mimeMessage);
            return true;
        }
        return false;
    }

    /**
     * 验证邮箱验证码，存入redis
     *
     * @param email 邮箱地址
     * @return 成功返回true，失败返回false
     */
    @Override
    public String getRedisCode(String email) {
        return redisTemplate.opsForValue().get(email);
    }

    /**
     * 移除redis中的验证码
     *
     * @param email 邮箱地址
     */
    @Override
    public void removeRedisCode(String email) {
        redisTemplate.delete(email);
    }
}